<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="80%" z-index="100">
    <!-- 表单区域 -->
    <el-form ref="form" :model="formData" label-width="120px" size="small">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="生产单号:" prop="orderNumber">
            <el-input v-model="formData.orderNumber" placeholder="SC00001378206" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品条码:" prop="productBarcode">
            <JSelectList kind="material" @change="handleProMaterialChange" :multi="false"
                         :value="formData.productBarcode"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称:" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商品名称" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量单位:" prop="commodityUnit">
            <el-input v-model="formData.commodityUnit" placeholder="请输入计量单位" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="多属性:" prop="sku">
            <el-input v-model="formData.sku" placeholder="" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订购数量:" prop="orderedQuantity">
            <el-input v-model="formData.orderedQuantity" placeholder="请输入订购数量" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产数量:" prop="producedQuantity">
            <el-input v-model="formData.producedQuantity" placeholder="请输入生产数量"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售订单号:" prop="salesOrderNumber">
            <el-input v-model="formData.salesOrderNumber" placeholder="请输入销售订单号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户原始单号:" prop="customerOriginalNumber">
            <el-input v-model="formData.customerOriginalNumber" placeholder="请输入客户原始单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计划完工:" prop="plannedCompletionDate">
            <el-date-picker
              v-model="formData.plannedCompletionDate"
              type="date"
              placeholder="请选择计划完工"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据备注:" prop="remarks">
            <el-input v-model="formData.remarks" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 所需物料表格 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="1、所需物料" name="materials">
          <div style="margin-bottom: 20px;">
            <el-button type="primary" @click="addMaterialRow">+ 插入行</el-button>
            <el-button type="danger" @click="removeSelectedMaterialRows" :disabled="selectedMaterialRows.length === 0">移除行</el-button>
          </div>
          <el-table :data="materialRows" border style="width: 100%"  @selection-change="handleMaterialSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="bomBarCode" label="条码" width="200">
              <template slot-scope="scope">
                <JSelectList kind="material" @change="(mBarCode) => handleBomMaterialChange(mBarCode, scope.row)" :multi="false"
                             :value="scope.row.bomBarCode"/>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称"/>
            <el-table-column prop="standard" label="规格"/>
            <el-table-column prop="model" label="型号"/>
            <el-table-column prop="inventory" label="库存"/>
            <el-table-column prop="commodityUnit" label="单位"/>
            <el-table-column prop="sku" label="多属性"/>
            <el-table-column prop="num" label="数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.num" placeholder="数量" @input="calculateCost(scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="purchasePrice" label="单价"/>
            <el-table-column prop="allPrice" label="费用"/>
            <el-table-column prop="remarks" label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" placeholder="备注"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="2、生产工序" name="processes">
          <div style="margin-bottom: 20px;">
            <el-button type="primary" @click="addProcessRow">+ 插入行</el-button>
            <el-button type="danger" @click="removeSelectedProcessRows" :disabled="selectedProcessRows.length === 0">移除行</el-button>
          </div>
          <el-table :data="processRows" border style="width: 100%" @selection-change="handleProcessSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="executionOrder" label="执行顺序" width="160">
              <template slot-scope="scope">
                <el-input v-model="scope.row.executionOrder" placeholder="请输入执行顺序"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="processName" label="工序名称" width="160">
              <template slot-scope="scope">
                <el-input v-model="scope.row.processName" placeholder="请输入工序名称"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="responsiblePerson" label="负责人" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.responsiblePerson" placeholder="请选择负责人" style="width: 100%;">
                  <el-option
                    v-for="person in responsiblePersonList"
                    :key="person.id"
                    :label="person.userName"
                    :value="person.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="billingMethod" label="计费方式" width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.billingMethod" placeholder="请选择计费方式">
                  <el-option label="计时" :value="0"></el-option>
                  <el-option label="计件" :value="1"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="laborCost" label="加工单价" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.laborCost" placeholder="请输入加工单价"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="requiredCost" label="所需费用">
              <template slot-scope="scope">
                {{ calculateProcessCost(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="plannedCompletionDate" label="计划完工时间" width="200">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.plannedCompletionDate"
                  type="date"
                  placeholder="请选择计划完工时间"
                  style="width: 100%"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 对话框底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="saveData">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {getAction, postAction, putAction} from "@api/manage";
import JSelectList from "@comp/jeecgbiz/JSelectList.vue";
import {findStockByDepotAndBarCode, getMaterialByBarCode, getUserList} from "@api/api";

export default {
  name: 'ProductionTaskAddDialog',
  components: {JSelectList},
  data() {
    return {
      responsiblePersonList: [],
      selectedMaterialRows: [],
      dialogVisible: false,
      dialogTitle: '新增生产任务',
      activeTab: 'materials',
      formData: {
        orderNumber: '',
        sku: '',
        customerOriginalNumber: '',
        productBarcode: '',
        orderedQuantity: 0,
        plannedCompletionDate: '',
        name: '',
        producedQuantity: 1,
        commodityUnit: '',
        salesOrderNumber: '',
        remarks: ''
      },
      materialRows: [
        { bomBarCode: '', name: '', standard: '', model: '', inventory: '', commodityUnit: '', sku: '', num: '', purchasePrice: '', allPrice: '', remarks: '' }
      ],
      processRows: [
        { executionOrder: '', processName: '', responsiblePerson: '', billingMethod: '', laborCost: '', requiredCost: '', plannedCompletionDate: '', remarks: '' }
      ],
      selectedProcessRows: [],
      isEdit: false,
      editId: null
    };
  },
  methods: {
    openDialog(row) {
      this.resetForm();
      this.dialogVisible = true;
      if (row) {
        // 编辑模式
        this.isEdit = true;
        this.editId = row.id;
        this.dialogTitle = '编辑生产任务';
        this.formData = {
          ...row,
        };
        this.getMaterialsByTaskId(row.id);
        this.getProcessesByTaskId(row.id);
      } else {
        // 新增模式
        this.isEdit = false;
        this.editId = null;
        this.dialogTitle = '新增生产任务';
        this.generateOrderNumber();
        this.initUser();
      }
    },
    closeDialog() {
      this.dialogVisible = false;
      this.resetForm();
    },
    resetForm() {
      this.formData = {
        orderNumber: '',
        sku: '',
        customerOriginalNumber: '',
        productBarcode: '',
        orderedQuantity: 0,
        plannedCompletionDate: '',
        name: '',
        producedQuantity: 1,
        commodityUnit: '',
        salesOrderNumber: '',
        remarks: ''
      };
      this.materialRows = [
        { bomBarCode: '', name: '', standard: '', model: '', inventory: '', commodityUnit: '', sku: '', num: '', purchasePrice: '', allPrice: '', remarks: '' }
      ];
      this.processRows = [
        { executionOrder: '', processName: '', responsiblePerson: '', billingMethod: '', laborCost: '', requiredCost: '', plannedCompletionDate: '', remarks: '' }
      ];
    },
    getMaterialsByTaskId(taskId) {
      getAction('/production/task/getMaterialByTaskId', { taskId }).then(res => {
          if (res && res.code === 200) {
            this.materialRows = res.data;
          }
      });
    },
    getProcessesByTaskId(taskId) {
      getAction('/production/task/getProcessByTaskId', { taskId }).then(res => {
        if (res && res.code === 200) {
          this.processRows = res.data;
        }
      });
    },
    addMaterialRow() {
      this.materialRows.push({
        bomBarCode: '',
        name: '',
        standard: '',
        model: '',
        inventory: '',
        commodityUnit: '',
        sku: '',
        num: '',
        purchasePrice: '',
        allPrice: '',
        remarks: ''
      });
    },
    handleMaterialSelectionChange(selection) {
      this.selectedMaterialRows = selection;
    },
    removeSelectedMaterialRows() {
      if (this.selectedMaterialRows.length > 0) {
        this.selectedMaterialRows.forEach(row => {
          const index = this.materialRows.indexOf(row);
          if (index > -1) {
            this.materialRows.splice(index, 1);
          }
        });
        this.selectedMaterialRows = [];
      }
    },
    saveData() {
      // 保存数据逻辑
      const params = {
        productionOrder: this.formData,
        productionMaterials: this.materialRows,
        productionProcesses: this.processRows
      };

      let request;
      if (this.isEdit) {
        // 编辑模式使用PUT请求
        params.productionOrder.id = this.editId;
        request = putAction('/production/task/update', params);
      } else {
        // 新增模式使用POST请求
        request = postAction('/production/task/add', params);
      }

      // 调用后台接口保存数据
      request.then(res => {
        if (res && res.code === 200) {
          this.$message.success(this.isEdit ? '编辑成功' : '保存成功');
          this.closeDialog();
          // 可以在这里触发刷新列表等操作
          this.$emit('save-success')
        } else {
          this.$message.error(res.message || (this.isEdit ? '编辑失败' : '保存失败'));
        }
      }).catch(err => {
        console.error(this.isEdit ? '编辑失败:' : '保存失败:', err);
        this.$message.error(this.isEdit ? '编辑失败' : '保存失败');
      });
    },
    // 添加生成单据编号的方法
    generateOrderNumber() {
      // 调用单据编号生成接口
      getAction('/sequence/buildNumber').then(res => {
        if (res && res.code === 200) {
          this.formData.orderNumber = "SC"+res.data.defaultNumber;
        }
      }).catch(err => {
        console.error('生成单据编号失败:', err);
      });
    },
    initUser() {
      getUserList({}).then((res)=>{
        if(res) {
          this.responsiblePersonList = res;
        }
      });
    },
    // 计算费用 = 数量 * 单价
    calculateCost(row) {
      const num = parseFloat(row.num) || 0;
      const price = parseFloat(row.purchasePrice) || 0;
      row.allPrice = (num * price).toFixed(2);
    },
    //选中生产商品信息查询
    handleProMaterialChange(mBarCode) {
      if (mBarCode) {
        this.formData.productBarcode = mBarCode;
        getMaterialByBarCode({ barCode: mBarCode, mpList: '' }).then((res) => {
          if (res.code === 200 && res.data && res.data[0]) { // 增加非空判断
            this.formData.name = res.data[0].name;
            this.formData.commodityUnit = res.data[0].commodityUnit;
            this.formData.sku = res.data[0].sku;
            this.proMaterialBomMaterialList(res.data[0].id);
            this.proMaterialBomProcessList(res.data[0].id);
          }
        }).catch((err) => {
          console.error('Error fetching material by barcode:', err);
          this.$message.error('获取商品信息失败');
        });
      }
    },
    //选中生产商品物料信息查询
    proMaterialBomMaterialList(proMaterialId) {
      getAction('/bom/getBomMaterialsByProductId', {productId: proMaterialId}).then((res) => {
        if (res.code === 200) {
          this.materialRows = res.data;
        } else {
          console.error('Failed to fetch material data:', res);
          this.$message.error('获取物料数据失败');
        }
      }).catch((err) => {
        console.error('Error fetching material data:', err);
        this.$message.error('获取物料数据失败');
      });
    },
    //选中生产商品工序信息查询
    proMaterialBomProcessList(proMaterialId) {
      getAction('/bom/getProductionProcessesByProductId', {productId: proMaterialId}).then((res) => {
        if (res.code === 200) {
          this.processRows = res.data;
        }else {
          console.error('Failed to fetch process data:', res);
          this.$message.error('获取工序数据失败');
        }
      }).catch((err) => {
        console.error('Error fetching process data:', err);
        this.$message.error('获取工序数据失败');
      })
    },
    // 选中物料条码时，更新该行其他数据
    handleBomMaterialChange(mBarCode, row) {
      if (mBarCode) {
        //更新商品基本信息
        getMaterialByBarCode({ barCode: mBarCode, mpList: '' }).then((res) => {
          if (res.code === 200 && res.data && res.data[0]) {
            const material = res.data[0];
            // 更新当前行的数据
            row.bomBarCode = mBarCode;
            row.name = material.name;
            row.standard = material.standard;
            row.model = material.model;
            row.commodityUnit = material.commodityUnit;
            row.sku = material.sku;
            row.purchasePrice = material.purchaseDecimal || 0;
            row.num = 1;
            // 计算费用
            this.calculateCost(row);
          } else {
            this.$message.error('未找到该物料信息');
          }
        }).catch((err) => {
          console.error('Error fetching material by barcode:', err);
          this.$message.error('获取物料信息失败');
        });
        //更新商品库存信息
        findStockByDepotAndBarCode({barCode: mBarCode}).then((res) => {
          if (res.code === 200 && res.data ) {
            row.inventory = res.data.stock;
          }else {
            this.$message.error('未找到该物料库存信息');
          }
        }).catch((err) => {
          console.error('Error fetching stock by barcode:', err);
          this.$message.error('获取物料库存信息失败');
        })
      }
    },
    addProcessRow() {
      this.processRows.push({
        executionOrder: '',
        processName: '',
        responsiblePerson: '',
        billingMethod: '',
        laborCost: '',
        requiredCost: '',
        plannedCompletionDate: '',
        remarks: ''
      });
    },
    handleProcessSelectionChange(selection) {
      this.selectedProcessRows = selection;
    },
    removeSelectedProcessRows() {
      if (this.selectedProcessRows.length > 0) {
        this.selectedProcessRows.forEach(row => {
          const index = this.processRows.indexOf(row);
          if (index > -1) {
            this.processRows.splice(index, 1);
          }
        });
        this.selectedProcessRows = [];
      }
    },
    calculateProcessCost(row) {
      const cost = parseFloat(row.laborCost) || 0;
      const quantity = parseFloat(this.formData.producedQuantity) || 0;
      row.requiredCost = (cost * quantity).toFixed(2);
      return row.requiredCost;
    }
  }
};
</script>

<style scoped>
/* 样式 */
</style>